import React, { useContext, Fragment, useState } from 'react';

import { useRequest } from 'umi';

import { Table, Button, Tooltip, Switch, message, Popover } from 'antd';

import { EditOutlined, CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons';

import cls from 'classnames';
import pageStyles from '@/common/pageLayout.less';
import { IDictionaryTableContent } from '../type';
import { getCompanyID, getPosIDs, getUserDepID, getUserID } from '@/utils';
import MyIcon from '@/components/MyIcon';
import { isDisplayDictionary, isOpenDictionary } from '../service';
import { DictionaryContext } from '../hooks';
import { DictionaryEdit } from './DictionaryTableEdit';

export const DictionaryTableContent: React.FC<IDictionaryTableContent> = ({ dataSource, loading }) => {
  const { prefixCls, selectKeys, searchTableValue, reloadTableDataSource, expandedRowKeys, commonDispatch, curRes } = useContext(
    DictionaryContext,
  );

  const [spinning, setSpinning] = useState(false);

  const [showDictionaryEdit, setShowDictionaryEdit] = useState(false);

  const [record, setRecord] = useState({});

  const onUpdateOpen = useRequest(
    (params) => {
      return isOpenDictionary(params);
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res.msgFlag) {
          message.success(res?.msg ?? '字典禁用成功');
        } else {
          message.error(res?.msg);
        }
        reloadTableDataSource(selectKeys?.[0]);
        setSpinning(false);
      },
    },
  );

  const onUpdateDisplay = useRequest(
    (params) => {
      return isDisplayDictionary(params);
    },
    {
      manual: true,
      onSuccess: (res) => {
        if (res && res.msgFlag) {
          message.success(res?.msg ?? '隐藏设置成功');
        } else {
          message.error(res?.msg);
        }
        reloadTableDataSource(selectKeys?.[0]);
        setSpinning(false);
      },
    },
  );

  const onSwitchOpen = (e: boolean, record: Record<string, any>) => {
    setSpinning(true);

    let isOpen = 0;

    if (e) {
      isOpen = 1;
    }

    const params = {
      id: record?.id,
      typeID: selectKeys?.[0],
      isOpen: isOpen,
      modifyerID: getUserID(),
      modifyPositionID: getPosIDs(),
      modifyDepartmentID: getUserDepID(),
      modifyCompanyID: getCompanyID(),
      versionNum: record?.versionNum,
    };

    onUpdateOpen.run(params);
  };

  const onSwitchDisplay = (e: boolean, record: Record<string, any>) => {
    setSpinning(true);
    let isDisplay = 0;

    if (e) {
      isDisplay = 1;
    }

    const params = {
      id: record?.id,
      typeID: selectKeys?.[0],
      isDisplay: isDisplay,
      modifyerID: getUserID(),
      modifyPositionID: getPosIDs(),
      modifyDepartmentID: getUserDepID(),
      modifyCompanyID: getCompanyID(),
      versionNum: record?.versionNum,
    };

    onUpdateDisplay.run(params);
  };

  const onOpenDictionaryEdit = () => {
    setShowDictionaryEdit(true);
  };

  const onCloseDictionaryEdit = () => {
    setShowDictionaryEdit(false);
    setRecord({});
  };

  const onEditClick = (records: Record<string, any>) => {
    const promise = new Promise((resolve, reject) => {
      setRecord(records);

      resolve(true);
    });

    promise.then((res) => {
      if (res) {
        onOpenDictionaryEdit();
      }
    });
  };

  const getTreeIcon = (flag: any) => {
    return (
      <a style={{ marginRight: 5 }}>
        {flag ? <MyIcon type={'icon-ic-normal-zidianguanli'} /> : <MyIcon type={'icon-icon-test2'} />}
      </a>
    );
  };

  const content = (record: any) => {
    return (
      <div style={{ color: '#000000D9' }}>
        <p>
          编号：
          {record?.id || '--'}
        </p>
        <p>
          名称：
          <span
            style={{
              color: record?.fontColor,
            }}
          >
            {record?.name}
          </span>
        </p>
        <p>
          简码：
          {record?.shortCode || '--'}
        </p>
        <p>
          状态：
          {record?.isOpen == 0 ? <span style={{ color: 'red' }}>禁用</span> : <span style={{ color: 'green' }}>启用</span>}
        </p>
        <p>
          显示：
          {record?.isDisplay == 0 ? <span style={{ color: 'red' }}>否</span> : <span style={{ color: 'green' }}>是</span>}
        </p>
        <p>
          排序：
          {record?.seq || '--'}
        </p>
      </div>
    );
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');
  const [showPopover, setShowPopover] = useState<boolean>(false);

  /**
   * 显示 隐藏 详情方法
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (showPopo: string, isOpen: boolean) => {
    setShowPopover(isOpen);
    setShowPopoverID(showPopo);
  };

  const columns: any = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 280,
      showSorterTooltip: false,
      render: (text: string, record: Record<string, any>) => {
        const searchLength = searchTableValue?.length;
        const startLocation = text?.search(searchTableValue);
        const textLength = text?.length;
        const beforeStr = text.slice(0, startLocation);
        const afterStr = text.slice(Number(searchLength) + Number(startLocation), textLength);
        return (
          <Popover
            placement="bottomLeft"
            content={content(record)}
            trigger={'hover'}
            title={'详细信息'}
            color={'rgb(222 222 222)'}
            overlayClassName={cls('dic-popover')}
            open={showPopover && showPopoverID == record?.id ? true : false}
          >
            <div
              style={{ display: 'flex', alignItems: 'center' }}
              onClick={() => {
                clickEyeDetail(record?.id, true);
              }}
              onMouseLeave={() => {
                clickEyeDetail(record?.id, false);
              }}
            >
              {getTreeIcon(record?.pID)}
              {startLocation < 0 ? (
                <div style={{ color: record?.fontColor ?? '#000' }} className={pageStyles['over-flow-hidden']}>
                  {text}
                </div>
              ) : (
                <div style={{ color: record?.fontColor ?? '#000' }} className={pageStyles['over-flow-hidden']}>
                  {beforeStr}
                  <span
                    style={{
                      background: 'rgb(255, 150, 50)',
                    }}
                  >
                    {searchTableValue}
                  </span>
                  {afterStr}
                </div>
              )}
            </div>
          </Popover>
        );
      },
    },
    {
      title: '简码',
      dataIndex: 'shortCode',
      key: 'shortCode',
      width: 200,
      showSorterTooltip: false,
      render: (text: string) => {
        return <span>{text ?? '--'}</span>;
      },
    },
    {
      title: '是否启用',
      dataIndex: 'isOpen',
      key: 'isOpen',
      width: 120,
      showSorterTooltip: false,
      render: (text: any, record: Record<string, any>) => {
        const isOpen = text == 1 ?? false;
        return (
          <Switch
            checked={isOpen}
            onChange={(e) => {
              onSwitchOpen(e, record);
            }}
            checkedChildren={'启用'}
            unCheckedChildren={'禁用'}
            disabled={!curRes?.['/dictionaryController/isOpen']}
          />
        );
      },
    },
    {
      title: '是否显示',
      dataIndex: 'isDisplay',
      key: 'isDisplay',
      width: 120,
      showSorterTooltip: false,
      render: (text: any, record: Record<string, any>) => {
        const isDisplay = text == 1 ?? false;
        return (
          <Switch
            checked={isDisplay}
            onChange={(e) => {
              onSwitchDisplay(e, record);
            }}
            checkedChildren={'显示'}
            unCheckedChildren={'隐藏'}
            disabled={!curRes?.['/dictionaryController/isDisplay']}
          />
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'seq',
      key: 'seq',
      width: 90,
      showSorterTooltip: false,
      sorter: (a: any, b: any) => a.seq - b.seq,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      showSorterTooltip: false,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className={pageStyles['over-flow-hidden']} style={{ maxWidth: 100 }}>
            {text || '--'}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      showSorterTooltip: false,
      render: (_text: string, record: Record<string, any>) => (
        <Fragment>
          {curRes?.['/dictionaryTypeController/edit'] ? (
            <Button
              size="small"
              icon={<EditOutlined />}
              onClick={() => onEditClick(record)}
              type={'link'}
              className="manageBtntTxtStyle"
            >
              编辑
            </Button>
          ) : (
            <>--</>
          )}
        </Fragment>
      ),
    },
  ];

  // 修改下拉展开图标
  const expandIcon = (props: any) => {
    if (props.record.children && props.record.children.length > 0) {
      if (props.expanded) {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretDownOutlined />
            </span>
          </span>
        );
      } else {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretRightOutlined />
            </span>
          </span>
        );
      }
    } else {
      return (
        <span
          style={{
            float: 'left',
            marginRight: '5px',
          }}
        >
          <span style={{ fontSize: '10px', visibility: 'hidden' }}>
            <CaretRightOutlined />
          </span>
        </span>
      );
    }
  };
  return (
    <>
      <div className={cls(prefixCls + 'table-content')}>
        <div className={cls('list-table')}>
          <Table
            size="small"
            columns={columns}
            bordered
            pagination={false}
            dataSource={dataSource}
            loading={spinning || loading}
            rowKey={(record) => record?.id}
            scroll={{ x: 800, y: 'true' }}
            expandIcon={expandIcon}
            expandable={{
              onExpandedRowsChange: (keys) => {
                commonDispatch({
                  type: 'edit-expandedRowKeys',
                  payload: keys,
                });
              },
              expandedRowKeys: expandedRowKeys,
            }}
          />
        </div>
      </div>

      {showDictionaryEdit && <DictionaryEdit onClose={onCloseDictionaryEdit} record={record} dataSource={dataSource} />}
    </>
  );
};
